﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TeamOPSchoolCup.Domain.DAL;
using TeamOPSchoolCup.Domain.Services;
using System.IO;
using TeamOPSchoolCup.Domain.POCO;
using TeamOPSchoolCup.Domain.POCO.Ranking;
using TeamOPSchoolCup.Web.Models;
using TeamOPSchoolCup.Domain.DTO;

namespace TeamOPSchoolCup.Web.Controllers
{
  public class HomeController : Controller
  {
    //
    // GET: /Home/

    public ActionResult Index()
    {
      TeamService.GetTeams();
      return View();
    }

    public ActionResult ImportPointsTemp()
    {
      return View();
    }

    //WARNING: Dirty code ahead
    //  Nesting-hell
    //  No use of services
    //  Doesn't account for first line being text
    [HttpPost]
    public ActionResult ImportPointsTemp(HttpPostedFileBase file)
    {
      //Might want to do errormessages =)
      if (file == null || file.ContentLength <= 0 || file.ContentType != "application/vnd.ms-excel") return RedirectToAction("Index");
      //Some hardcoded stuff, for now; User should be able to configure this stuff
      PointsImport pi = new PointsImport() { Event = EventService.GetEvent("long-jumping"), CompetitionYear = 2013 };
      int pointsColumn = 0;
      int boysColumn = 1;
      int girlsColumn = 2;

      string path = Path.Combine(Server.MapPath("~/Upload"), file.FileName);
      file.SaveAs(path);

      string line;
      using (StreamReader r = new StreamReader(path))
      {
        while ((line = r.ReadLine()) != null)
        {
          if (!ModelState.IsValid) continue;
          string[] values = line.Split(';');
          if (String.IsNullOrWhiteSpace(values[pointsColumn])) continue;
          int pointValue = Int32.Parse(values[pointsColumn]);
          pi.Lines.Add(new PointsImport.ImportLine
          {
            PointValue = pointValue,
            BoysMeasure = (String.IsNullOrWhiteSpace(values[boysColumn]) ? 0 : Double.Parse(values[boysColumn])),
            GirlsMeasure = (String.IsNullOrWhiteSpace(values[girlsColumn]) ? 0 : Double.Parse(values[girlsColumn]))
          });
        }
      }
      RankingService.ImportPoints(pi);

      return RedirectToAction("Index");
    }

    //TEMP
    public ActionResult RankingUpdateAllTheThings()
    {
      //RankingService.UpdateAllTheThings();

      return RedirectToAction("Index");
    }
  }
}
